import { uploadFileMethod } from '@/utils/upload'
// 引入 Loading 服务
import { Loading } from 'element-ui'
import {listByTemplateId} from "@/api/shipRegistrationManagement/singleShip/singleShip";
import dictionary from "@/utils/dictionary";
import {treeByTemplate} from "@/api/sys/dict/data";
import {getDropDownCz} from "@/api/dispatch/lockPersonalitySetting/lockPersonalitySetting";

const defaultSettings = require('../settings')
/**
 * 通用js方法封装处理
 * Copyright (c) 2019 ruoyi
 */

// 日期格式化
export function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time
        .replace(new RegExp(/-/gm), '/')
        .replace('T', ' ')
        .replace(new RegExp(/\.[\d]{3}/gm), '')
    }
    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

// 表单重置
export function resetForm(refName) {
  if (this.$refs[refName]) {
    this.$refs[refName].resetFields()
  }
}

// 添加日期范围
export function addDateRange(params, dateRange, propName) {
  let search = params
  search.params =
    typeof search.params === 'object' &&
    search.params !== null &&
    !Array.isArray(search.params)
      ? search.params
      : {}
  dateRange = Array.isArray(dateRange) ? dateRange : []
  if (typeof propName === 'undefined') {
    search.params['createdDateStart'] = dateRange[0]
    search.params['createdDateEnd'] = dateRange[1]
  } else {
    search.params['begin' + propName] = dateRange[0]
    search.params['end' + propName] = dateRange[1]
  }
  return search
}

export function addDateRangeNew(params, dateRange, propName) {
  const search = params
  dateRange = Array.isArray(dateRange) ? dateRange : []
  if (typeof propName === 'undefined') {
    search['createdDateStart'] = dateRange[0]
    search['createdDateEnd'] = dateRange[1]
  } else {
    search[propName+'StartTime'] = dateRange[0]
    search[propName+'EndTime'] = dateRange[1]
  }
  return search
}

// 回显数据字典
export function selectDictLabel(datas, value) {
  if (value === undefined) {
    return ''
  }
  var actions = []
  Object.keys(datas).some(key => {
    if (datas[key].value == '' + value) {
      actions.push(datas[key].label)
      return true
    }
  })
  if (actions.length === 0) {
    actions.push(value)
  }
  return actions.join('')
}

// 回显数据字典（字符串、数组）
export function selectDictLabels(datas, value, separator) {
  if (value === undefined || value.length === 0) {
    return ''
  }
  if (Array.isArray(value)) {
    value = value.join(',')
  }
  var actions = []
  var currentSeparator = undefined === separator ? ',' : separator
  var temp = value.split(currentSeparator)
  Object.keys(value.split(currentSeparator)).some(val => {
    var match = false
    Object.keys(datas).some(key => {
      if (datas[key].value == '' + temp[val]) {
        actions.push(datas[key].label + currentSeparator)
        match = true
      }
    })
    if (!match) {
      actions.push(temp[val] + currentSeparator)
    }
  })
  return actions.join('').substring(0, actions.join('').length - 1)
}

// 字符串格式化(%s )
export function sprintf(str) {
  var args = arguments,
    flag = true,
    i = 1
  str = str.replace(/%s/g, function () {
    var arg = args[i++]
    if (typeof arg === 'undefined') {
      flag = false
      return ''
    }
    return arg
  })
  return flag ? str : ''
}

// 转换字符串，undefined,null等转化为""
export function parseStrEmpty(str) {
  if (!str || str == 'undefined' || str == 'null') {
    return ''
  }
  return str
}

// 数据合并
export function mergeRecursive(source, target) {
  for (var p in target) {
    try {
      if (target[p].constructor == Object) {
        source[p] = mergeRecursive(source[p], target[p])
      } else {
        source[p] = target[p]
      }
    } catch (e) {
      source[p] = target[p]
    }
  }
  return source
}

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'menuParentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
export function handleTree(data, id, parentId, children) {
  let config = {
    id: id || 'id',
    parentId: parentId || 'menuParentId',
    childrenList: children || 'children'
  }
  let childrenListMap = {}
  let nodeIds = {}
  let tree = []

  for (let d of data) {
    let parentId = d[config.parentId]
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = []
    }
    nodeIds[d[config.id]] = d
    childrenListMap[parentId].push(d)
  }

  for (let d of data) {
    let parentId = d[config.parentId]
    if (nodeIds[parentId] == null) {
      tree.push(d)
    }
  }

  for (let t of tree) {
    adaptToChildrenList(t)
  }

  function adaptToChildrenList(o) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]]
    }
    if (o[config.childrenList]) {
      for (let c of o[config.childrenList]) {
        adaptToChildrenList(c)
      }
    }
  }
  return tree
}

/**
 * 参数处理
 * @param {*} params  参数
 */
export function tansParams(params) {
  let result = ''
  for (const propName of Object.keys(params)) {
    const value = params[propName]
    var part = encodeURIComponent(propName) + '='
    if (value !== null && value !== '' && typeof value !== 'undefined') {
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          if (
            value[key] !== null &&
            value[key] !== '' &&
            typeof value[key] !== 'undefined'
          ) {
            let params = propName + '[' + key + ']'
            var subPart = encodeURIComponent(params) + '='
            result += subPart + encodeURIComponent(value[key]) + '&'
          }
        }
      } else {
        result += part + encodeURIComponent(value) + '&'
      }
    }
  }
  return result
}

// 验证是否为blob格式
export async function blobValidate(data) {
  try {
    const text = await data.text()
    JSON.parse(text)
    return false
  } catch (error) {
    return true
  }
}

//上传文件的方法
//{}
export async function requestUploadMethod(fileObj) {
  let uploadData = new FormData()
  uploadData.append('file', fileObj.file)
  //add fjyw
  uploadData.append('fjyw', fileObj.fjyw ||'')

  return await new Promise((resolve, reject) => {
    uploadFileMethod(uploadData)
      .then(res => {
        resolve(res)
      })
      .catch(onerror => {
        reject(onerror)
      })
  })
}

//处理登记号前缀
export function handlerDjhPrefix(hx, cblx, qtCblx = '') {
  let hx_prefix = ''
  let cblx_prefix = ''
  if (hx && hx == '1') {
    hx_prefix = 'S'
  }
  if (hx && hx == '2') {
    hx_prefix = 'X'
  }
  if (cblx && cblx === 1) {
    cblx_prefix = 'HL'
  }
  if (cblx && cblx === 2) {
    cblx_prefix = 'ZX'
  }
  if (cblx && cblx === 3) {
    cblx_prefix = 'CD'
  }
  if (cblx && cblx === 4) {
    cblx_prefix = 'QT'
  }
  return hx_prefix.concat(cblx_prefix).concat(qtCblx)
}

export function baseColorfullLoading(wer, text) {
  const loading = Loading.service({
    // 声明一个loading对象
    lock: true, // 是否锁屏
    text: text, // 加载动画的文字
    spinner: 'inner-circles-loader', // 引入的loading图标
    background: 'rgba(0,0,0,0.7)', // 背景颜色
    target: document.querySelector(wer)
  })
  return loading
}

/** 判断是否是数组
 * @param {Object} value
 * 返回true或false
 */
export function isArrayFn(value) {
  if (typeof Array.isArray === 'function') {
    return Array.isArray(value)
  }
  return Object.prototype.toString.call(value) === '[object Array]'
}

/**
 * 比较两个数组是否相等
 *@param{Arry}arr1 需要比较的数组1
 *@param{Arry}arr2 需要比较的数组2
 */
export function equalsArr(arr1 = [], arr2 = []) {
  if (!isArrayFn(arr1) || !isArrayFn(arr2)) return
  if (JSON.stringify(arr1) == JSON.stringify(arr2)) return true
  return false
}

// 数组去重
export function unique(data = [], key) {
  if (!data) return
  const res = new Map()
  return data.filter(a => !res.has(a[key]) && res.set(a[key], 1))
}

/** 判断是否是对象
 * @param {Object} value
 * 返回true或false
 */
export function isObject(value) {
  if (Object.prototype.toString.call(value) === '[object Object]') {
    return true
  }
  return false
}
/**
 * 根据传入字符串不同获取对应的按钮样式,可传入多个按钮，用，隔开
 * */
export function getButtonObj(name) {
  const strArr = name.split(',')
  const data = []
  for (const i in strArr) {
    for (const k in defaultSettings.buttonObject) {
      if (k === strArr[i]) {
        data.push(defaultSettings.buttonObject[k])
      }
    }
  }
  return data
}
// 字典值转换成中文
// 根据类型查询字典值
export function queryDictByKey(dict, key) {
  if (key == null && key == '') {
    return null
  }
  try {
    for (let i = 0; i < dict.length; i++) {
      if (dict[i].key == key) {
        return dict[i].value
      }
    }
  } catch (e) {
    return null
  }
}

// 根据字典类型查询字典值
export async function initDictOptionsUtil(dictType){
  // 获取船舶类型字典值
  let options =[]
  if(this.$store.getters.dictDataStore){
    options = queryDictByKey(this.$store.getters.dictDataStore,dictType)
  }
  let dataArr = []
  if(options){
    dataArr = options
  }else{
    if(dictionary[dictType].isCascader){
      await treeByTemplate({templateId:dictionary[dictType].templateId}).then(({ data }) => {
        this.$store.dispatch('dictTemplate/setDictTemplate', {
          key: dictType,
          value: data
        })
        dataArr = data
      })
    }else{
      await listByTemplateId({templateId:dictionary[dictType].templateId}).then(({ data }) => {
        this.$store.dispatch('dictTemplate/setDictTemplate', {
          key: dictType,
          value: data
        })
        dataArr = data
      })
    }

  }
  return dataArr
}

//2023-4-10 数字金额大写
export function numberToCapitalLetter(num){
  //add 2023-5-22
  if (num == undefined){
    return ''
  }

  if (num == 0){
    return '零元整'
  }
  let minus = ''
  let m_str= ''
  const text = num.toString()
  const zh ='零壹贰叁肆伍陆柒捌玖'
  if (text.indexOf("-") === 0){
    num = text.replace('-', '')
    minus = '负'
  }
  let money_num = Number(num);
  let money =Math.round(money_num * 100).toString(10)
  const len = money.length
  for (let i = 0; i<len; i++){
    m_str = m_str + zh.charAt(parseInt(money.charAt(i))) + sitToUnit(len - i -1)
  }
  m_str = m_str.replace("零分", '')
  m_str = m_str.replace("零角", '零')
  let yy = 0;
  while (true){
    let len = m_str.length
    m_str = m_str.replace("零元",'元') //圆
    m_str = m_str.replace("零万",'万')
    m_str = m_str.replace("零亿",'亿')
    m_str = m_str.replace("零仟",'零')
    m_str = m_str.replace("零佰",'零')
    m_str = m_str.replace("零零",'零')
    m_str = m_str.replace("零拾",'零')
    m_str = m_str.replace("亿万",'亿零')
    m_str = m_str.replace("万仟",'万零')
    m_str = m_str.replace("仟佰",'仟零')
    yy = m_str.length
    if (yy === len){
      break
    }
  }
  yy = m_str.length
  if(m_str.charAt(yy - 1) ==='零'){
    m_str =m_str.substring(0, yy-1)
  }
  yy = m_str.length
  if (m_str.charAt(yy - 1) === '元'){ //圆
    m_str =m_str +'整'
  }
  return minus + m_str

}
function sitToUnit(a){
  if (a > 10){
    a = a -8
    return (this.sitToUnit(a))
  }
  const zh = '分角元拾佰仟万拾佰仟亿' //圆
  return zh.charAt(a)
}

